import axios from 'axios'
// import store from '@/store'
import storage from 'store'
import notification from 'ant-design-vue/es/notification'
import modal from 'ant-design-vue/es/modal'
import { VueAxios } from './axios'
import router from '../router'
// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: process.env.NODE_ENV === 'production' ? 'http://172.16.11.36:8888/api' : '/api',
  // 47.93.47.20
  // 172.16.11.36

  timeout: 60000, // 请求超时时间
  withCredentials: true,
  headers: {
    'Content-Type' : 'application/x-www-form-urlencoded;charset=UTF-8'
  }
})

// 异常拦截处理器
const errorHandler = (error) => {
  console.log(router)
  if (error.response) {
    const data = error.response.data
    // 从 localstorage 获取 token
    const token = storage.get('Access-Token')
    if (error.response.status === 401) {
      modal.destroyAll()
      if(router.history.current.name == 'login'){

      }else{
        modal.confirm({
          title: '错误',
          content: '登录已超时，请重新登录！',
          centered: true,
          onOk() {
            router.push({path: '/'})
          },
          onCancel() {},
        })
      }
    }
    if (error.response.status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message
      })
    }
    if (error.response.status === 500) {
      notification.error({
        message: '错误',
        description: data.error_description
      })
    }
  }
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
  const token = storage.get('Access-Token')
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    if( config.headers.Authorization == 'none'){
      config.headers['Authorization'] = ""
    }else{
      config.headers['Authorization'] = "Bearer " + token
    }
  }
  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  return response.data
}, errorHandler)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, request)
  }
}

export default request

export {
  installer as VueAxios,
  request as axios
}
